<template>
  <Modal
    :width="680"
    :title="title"
    :visible="visible"
    :centered="true"
    @cancel="onCancel"
    @ok="handleSubmit"
    okText="提交"
  >
    <Form ref="formRef" :model="model" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
      <template v-if="category">
        <FormItem label="ID">
          <TypographyText>{{ model?.id }}</TypographyText>
          <Divider type="vertical" />
          <TypographyText :copyable="true">
            {{ model?._id }}
          </TypographyText>
        </FormItem>
        <FormItem label="发布于">
          {{ stringToYMD(model?.create_at) }}
        </FormItem>
        <FormItem label="最后修改于">
          {{ stringToYMD(model?.update_at) }}
        </FormItem>
      </template>
      <FormItem label="分类名称" name="name" extra="这将是它在站点上显示的名字">
        <a-input v-model:value="model.name" placeholder="分类名称"></a-input>
      </FormItem>
      <FormItem
        label="分类别名"
        name="slug"
        extra="“别名” 是在 URL 中使用的别称，建议小写，字母、数字、连字符（-）"
      >
        <a-input v-model:value="model.slug" placeholder="分类别名"></a-input>
      </FormItem>
      <FormItem label="父分类" name="pid" extra="可以选择父级分类">
        <TreeSelect
          v-model:value="model.pid"
          treeDefaultExpandAll
          :treeData="[
            {
              label: '无',
              key: 'null',
              value: CATEGORY_NULL_VALUE,
            },
            ...tree,
          ]"
        ></TreeSelect>
      </FormItem>
      <FormItem label="分类描述" name="description">
        <a-textarea v-model:value="model.description" :rows="4" placeholder="分类描述"></a-textarea>
      </FormItem>
      <FormItem label="自定义扩展" extra="可以为当前标签增加自定义扩展属性，如：icon、background">
        <FormDataKeyValue :value="model.extends" />
      </FormItem>
    </Form>
  </Modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import type { UnwrapRef, PropType } from 'vue'
import type { Category as CategoryType } from '@/constants/category'
import type { TreeNodeProps } from 'ant-design-vue/es/vc-tree'
import { stringToYMD, timestampToYMD } from '@/transformers/date'
import FormDataKeyValue from '@/components/FormDataKeyValue/index.vue'
import {
  Divider,
  Form,
  FormInstance,
  FormItem,
  Modal,
  TreeSelect,
  TypographyText,
} from 'ant-design-vue'

const CATEGORY_NULL_VALUE = 'null'

const props = defineProps({
  title: {
    type: String,
    required: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  visible: {
    type: Boolean,
    default: false,
  },
  category: {
    type: Object as PropType<CategoryType | null>,
  },
  tree: {
    type: Array<TreeNodeProps>,
    required: true,
  },
  categories: {
    type: Array<CategoryType>,
    default: [],
  },
  onCancel: {
    type: Function as PropType<(e: MouseEvent) => void>,
    required: true,
  },
  onSubmit: {
    type: Function,
    required: true,
  },
})

const formRef = ref<FormInstance>()
const model: UnwrapRef<CategoryType> = reactive({
  id: undefined,
  _id: undefined,
  pid: null,
  name: '',
  slug: '',
  description: '',
  update_at: '',
  create_at: '',
  children: [],
  extends: [],
  articles_count: 0,
})
// const rules = {
//   name: [{ required: true, message: "请输入内容" }],
//   slug: [{ required: true, message: "请输入内容" }],
//   description: [{ required: true, message: "请输入内容" }],
// };
// const handleChange = (value: any) => {
// };

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (props.category) {
        model.id = props.category.id
        model._id = props.category._id
        model.pid = props.category.pid ?? CATEGORY_NULL_VALUE
        model.name = props.category.name
        model.slug = props.category.slug
        model.description = props.category.description
        model.update_at = props.category.update_at
        model.create_at = props.category.create_at
        model.children = props.category.children
        model.extends = props.category.extends
        model.articles_count = props.category.articles_count
      } else {
        model.name = ''
        model.slug = ''
        model.description = ''
        model.extends = [
          {
            name: 'icon',
            value: 'icon-category',
          },
        ]
        model.update_at = timestampToYMD(new Date().getTime())
        model.create_at = timestampToYMD(new Date().getTime())
      }
    } else {
      formRef.value?.resetFields()
    }
  }
)

const handleSubmit = () => {
  formRef.value
    ?.validate()
    .then(() => {
      props.onSubmit({
        ...model,
        pid: model.pid === CATEGORY_NULL_VALUE ? null : model.pid,
      })
    })
    .catch(() => {
      console.log('error')
    })
}
</script>

<style lang="less" scoped>
.announcement {
  .toolbar {
    display: flex;
    justify-content: space-between;

    .select {
      width: 130px;
    }
    .search {
      width: 200px;
    }
  }
}
</style>
